package com.sanjishu.enterlab.electricity.sale.controller;

import com.sanjishu.enterlab.electricity.sale.domain.User;
import com.sanjishu.enterlab.electricity.sale.service.MessageService;
import com.sanjishu.enterlab.electricity.sale.service.UserService;

import com.sanjishu.enterlab.electricity.sale.service.VerifyCodeService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
public class SignUpController {

    @Autowired
    private MessageService messageService;
    @Autowired
    private UserService userService;
    @Autowired
    private VerifyCodeService verifyCodeService;

    @RequestMapping(value = "signup", method = RequestMethod.GET)
    public String SignUp() {
        return "signup";
    }


    @RequestMapping(value = "signsuc", method = RequestMethod.POST)
    @ResponseBody
    public Response addUser(String phone, String password, String saler){
        User user = userService.insert(phone,DigestUtils.md5Hex(password), saler, User.TYPE_USER, phone);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(phone, DigestUtils.md5Hex(password));
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            return Response.getError(e.getMessage());
        }
        return Response.getSuccess(user);
    }

    @RequestMapping(value = "sendMessage", method = RequestMethod.POST)
    @ResponseBody
    public Response sendMessage(String phone) {
        try {
            User user = userService.findByPhone(phone);
            if (user != null) {
                return Response.getError("您已经注册过了，如忘记密码请至登录页面找回密码。");
            } else {
                messageService.sendCode(phone);
                return Response.buildSuccess("发送成功");
            }
        } catch (Exception e) {
            return Response.getError(e.getMessage());
        }
    }

    @RequestMapping(value = "checkCode", method = RequestMethod.POST)
    @ResponseBody
    public Response checkCode(String phone, String secCode) {
        return verifyCodeService.checkCode(phone, secCode);
    }

}
